package com.javachmapi.pay.util;

import java.util.*;

public class Sign {

	/**
	 * 微信支付签名算法sign，带编码格式
	 */
	@SuppressWarnings({ "rawtypes"})
	public static String createSign(String characterEncoding, Map<Object, Object> map, String key) {
		StringBuffer sb = new StringBuffer();
		String[] keyArr = (String[]) map.keySet().toArray(new String[map.keySet().size()]);//获取map中的key转为array
		Arrays.sort(keyArr);//对array排序
		for (int i = 0, size = keyArr.length; i < size; ++i) {
			if ("sign".equals(keyArr[i])) {
				continue;
			}
			sb.append(keyArr[i] + "=" + map.get(keyArr[i]) + "&");
		}
		sb.append("key=" + key);
		String sign = Md5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}

	/**
	 * 微信支付签名算法sign
	 */
	public static String getSign(Map<Object, Object> map, String key) {
		StringBuffer sb = new StringBuffer();
		String[] keyArr = (String[]) map.keySet().toArray(new String[map.keySet().size()]);//获取map中的key转为array
		Arrays.sort(keyArr);//对array排序
		for (int i = 0, size = keyArr.length; i < size; ++i) {
			if ("sign".equals(keyArr[i])) {
				continue;
			}
			sb.append(keyArr[i] + "=" + map.get(keyArr[i]) + "&");
		}
		sb.append("key=" + key);
		String sign = Md5Util.string2MD5(sb.toString());
		return sign;
	}
}
